package com.deer.wms.system.manage.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deer.wms.file.model.FileInfo;
import com.deer.wms.file.service.FileService;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.project.root.constant.Constants;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.project.root.service.SuperServiceImpl;
import com.deer.wms.project.root.util.DateUtils;
import com.deer.wms.project.root.util.MD5Utils;
import com.deer.wms.project.root.util.RandomUtil;
import com.deer.wms.system.manage.dao.UserInfoMapper;
import com.deer.wms.system.manage.model.user.*;
import com.deer.wms.system.manage.service.UserInfoService;
import com.deer.wms.system.manage.service.UserOrganizationService;
import com.deer.wms.system.manage.service.UserRoleService;
import com.deer.wms.system.manage.service.WareUserService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author guo
 * @since 2018/8/11
 */
@Service
@Transactional
public class UserInfoServiceImpl extends SuperServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    private static Logger logger = LoggerFactory.getLogger(UserInfoServiceImpl.class);

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private UserOrganizationService userOrganizationService;

    @Autowired
    private WareUserService wareUserService;

    @Autowired
    private FileService fileService;

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public List<UserListVO> findUserFormList(UserInfoCriteria criteria) {
        List<UserListVO> list = userInfoMapper.selectUserFormList(criteria);
        return list;
    }

    @Override
    public UserInfo findUserInfoByAccount(String account) {

        UserInfo userInfo = userInfoMapper.selectUserInfo(account);
        return userInfo;
    }

    @Override
    public UserInfo findInvalidUserInfoByAccount(String account) {
        QueryWrapper<UserInfo> qw = new QueryWrapper<>();
        qw.eq("account", account).eq("state", "invalid");
        UserInfo userInfo = this.getOne(qw);
        return userInfo;
    }

    @Override
    public UserDetail findUserDetailByAccount(String account) {
        if (StringUtils.isEmpty(account)) {
            return null;
        }
        return userInfoMapper.selectUserDetailByAccount(account);
    }

    @Override
    public UserInfoDetailVO findUserInfoDetailByUserId(Integer userId) {
        if (null == userId) {
            return null;
        }
        return userInfoMapper.selectUserInfoDetailVOByUserId(userId);
    }

    @Override
    public UserInfo validate(String account, String password) {
        // 验证账户是否存在

        UserInfo userInfo = userInfoMapper.selectUserInfo(account);

        if (null == userInfo || !Constants.INFO_STATE_NORMAL.equals(userInfo.getState())) {
            throw new ServiceException(CommonCode.SERVICE_ERROR, "此账号已禁用");
        }

        // 验证密码是否正确
        String loginPassword = MD5Utils.encryptPassword(userInfo.getAccount(), password, userInfo.getSalt());
        if (!loginPassword.equals(userInfo.getPassword())) {
            throw new ServiceException(CommonCode.SERVICE_ERROR, "登录账号或密码错误");
        }

        // 验证账号状态是否正常
        if (Constants.ACCOUNT_STATUS_DISABLE.equals(userInfo.getAccountStatus())) {
            throw new ServiceException(CommonCode.SERVICE_ERROR, "登录账号被锁定");
        }

        // 验证账号信息状态是否正常
        if (!Constants.INFO_STATE_NORMAL.equals(userInfo.getState())) {
            throw new ServiceException(CommonCode.SERVICE_ERROR, "登录账号状态异常，请与系统管理员联系");
        }

        return userInfo;
    }


    @Override
    public List<UserInfoDto> findUserByWareId(Integer wareId) {
        return userInfoMapper.findUserByWareId(wareId);
    }

    @Override
    public void modifyPassword(UserPassword userPassword, CurrentUser currentUser) {
        UserInfo userInfo = findUserInfoByAccount(currentUser.getAccount());
        String oldPassword = MD5Utils.encryptPassword(userInfo.getAccount(), userPassword.getOldPassword(),
                userInfo.getSalt());
        if (ObjectUtil.notEqual(oldPassword, userInfo.getPassword())) {
            throw new ServiceException(CommonCode.SERVICE_ERROR, "旧密码不正确");
        }

        String salt = RandomUtil.generateString(10);
        userInfo.setPassword(MD5Utils.encryptPassword(currentUser.getAccount(), userPassword.getPassword(), salt));
        userInfo.setSalt(salt);
        userInfo.setModifyUserId(currentUser.getUserId());
        userInfo.setModifyTime(DateUtils.getNowDateTimeString());

        super.updateById(userInfo);
    }

    @Override
    public void modifyUserData(UserData userData, CurrentUser currentUser) {
        // 修改个人信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(currentUser.getUserId());
        userInfo.setEmail(userData.getEmail());

        // 如果头像图片文件不为空，说明要修改头像图片
        if (null != userData.getIconUrlFile()) {
            // 删除原有的头像图片
            if (!StringUtils.isEmpty(currentUser.getIconUrl())) {
                fileService.deleteFileByRelativePath(currentUser.getIconUrl());
            }

            String savePath = "/user/" + userInfo.getUserId();
            FileInfo fileInfo = fileService.createFile(userData.getIconUrlFile(), savePath, true);
            userInfo.setIconUrl(fileInfo.getUrl());
        }
        // super.updateById(userInfo);
        // 邮箱和头像地址只有一个不为空，责进行修改
        if (!(StringUtils.isEmpty(userInfo.getIconUrl()) && StringUtils.isEmpty(userInfo.getEmail()))) {
            userInfoMapper.updateUserInfoById(userInfo);
        }
    }

    @Override
    public void modifyUserInfoAccountState(Integer userId, String sate, CurrentUser currentUser) {
        UserInfo userInfo = new UserInfo();
        // 先查询出用户数据--再做修改
        userInfo=userInfoMapper.selectById(userId);
        userInfo.setUserId(userId);
        userInfo.setAccountStatus(sate);
        userInfo.setModifyUserId(currentUser.getUserId());
        userInfo.setModifyTime(DateUtils.getNowDateTimeString());
        super.updateById(userInfo);
    }

    @Override
    public void modifyUserInfoState(Integer userId, String sate, CurrentUser currentUser) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setState(sate);
        userInfo.setModifyUserId(currentUser.getUserId());
        userInfo.setModifyTime(DateUtils.getNowDateTimeString());
        super.updateById(userInfo);
    }

    @Override
    public void retrievalPassword(UserPasswordRetrieval retrieval) {
        UserInfo userInfo = new UserInfo();
        userInfo.setAccount(retrieval.getMobile());
        userInfo.setState("normal");
        userInfo.setAccountStatus("enable");
//		List<UserInfo> users = userInfoMapper.select(userInfo);
        UserInfo user = userInfoMapper.selectUserInfo(retrieval.getMobile());
        String salt = RandomUtil.generateString(10);
        // UserInfo userInfo = findUserInfoByAccount(retrieval.getMobile());
        if (null == user) {
            throw new ServiceException(CommonCode.SERVICE_ERROR, "手机号码或邮箱未注册");
        }
        if (null != user && Constants.INFO_STATE_DELETED.equals(user.getState())) {
            throw new ServiceException(CommonCode.SERVICE_ERROR, "账号已被删除");
        }
        if (null != user && Constants.ACCOUNT_STATUS_DISABLE.equals(user.getAccountStatus())) {
            throw new ServiceException(CommonCode.SERVICE_ERROR, "账号已被停用");
        }
        if (null != user && !Constants.ACCOUNT_STATUS_DISABLE.equals(user.getAccountStatus())
                && !Constants.INFO_STATE_DELETED.equals(user.getState())) {
            BeanUtils.copyProperties(user, userInfo);
        }
        userInfo = user;
        userInfo.setPassword(MD5Utils.encryptPassword(userInfo.getAccount(), retrieval.getPassword(), salt));
        userInfo.setPassword(retrieval.getPassword());
        userInfo.setSalt(salt);
        userInfo.setModifyUserId(userInfo.getUserId());
        userInfo.setModifyTime(DateUtils.getNowDateTimeString());
        super.updateById(userInfo);
    }


    @Override
    public void createUserInfo(UserInfoCreate create, CurrentUser currentUser) {
        // 保存用户信息和账户信息
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(create, userInfo);
        String salt = RandomUtil.generateString(10);
//		userInfo.setAccount(create.getMobile());
        userInfo.setPassword(MD5Utils.encryptPassword(userInfo.getAccount(), create.getPassword(), salt));
//        userInfo.setPassword(create.getPassword());
        userInfo.setSalt(salt);
        userInfo.setCreateUserId(currentUser.getUserId());
        userInfo.setCreateTime(DateUtils.getNowDateTimeString());
        userInfo.setModifyTime(DateUtils.getNowDateTimeString());
        userInfo.setIsAdmin(0);
        if (StringUtils.isEmpty(userInfo.getUrl())) {
            userInfo.setUrl("/homepage");
        }
        super.save(userInfo);
    }

    @Override
    public void insertUser(UserVo t) {
        // 保存用户信息和账户信息
        UserInfo userInfo = new UserInfo();
        String salt = RandomUtil.generateString(10);
		userInfo.setAccount(t.getUserCode());
        userInfo.setUserType("1");
        userInfo.setGender(1);
        int radom1 = (int)(Math.random() * 999999);
        int radom2 = (int)(Math.random() * 99999);
        String mobile = ""+radom1 + radom2;
        userInfo.setMobile(mobile);
        userInfo.setOrg(t.getOrg());
        userInfo.setUserName(t.getUserName());
        userInfo.setPassword(MD5Utils.encryptPassword(userInfo.getAccount(), "123", salt));
        userInfo.setSalt(salt);
        userInfo.setCreateUserId(1);
        userInfo.setCreateTime(DateUtils.getNowDateTimeString());
        userInfo.setModifyTime(DateUtils.getNowDateTimeString());
        userInfo.setIsAdmin(0);
        if (StringUtils.isEmpty(userInfo.getUrl())) {
            userInfo.setUrl("/homepage");
        }
        super.save(userInfo);
//        UserInfo userInfo = new UserInfo();
//        userInfo.setPassword(MD5Utils.encryptPassword(userInfo.getAccount(), "123", "A1KaNOuS6f"));
//        userInfo.setErpId(t.getErpId());
//        userInfo.setOrg(t.getOrg());
//        userInfo.setUserName(t.getUserName());
//        userInfo.setAccount(t.getUserCode());
//        userInfo.setSalt("A1KaNOuS6f");
//        userInfo.setUserType("1");
    }

    @Override
    public void deleteByUserId(Integer userId) {
        userOrganizationService.deleteByUserId(userId);
        userRoleService.deleteByUserId(userId);
        wareUserService.deleteByUserId(userId);
        userInfoMapper.deleteByUserId(userId);
    }


    @Override
    public void modifyUserInfo(UserInfoModify modify, CurrentUser currentUser) {
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(modify, userInfo);
        // 可以去数据库先查询一遍 再赋值一些UserInfoModify没有的字段
        UserInfo user=userInfoMapper.selectById(modify.getUserId());
        userInfo.setSalt(user.getSalt());
        userInfo.setUserType(user.getUserType());
        userInfo.setAccountStatus(user.getAccountStatus());
        userInfo.setState(user.getState());
        userInfo.setCreateUserId(user.getCreateUserId());
        userInfo.setCreateTime(user.getCreateTime());
        userInfo.setIsAdmin(user.getIsAdmin());
        userInfo.setDeptId(user.getDeptId());

        userInfo.setModifyUserId(currentUser.getUserId());
        userInfo.setModifyTime(DateUtils.getNowDateTimeString());
        super.updateById(userInfo);
    }

    @Override
    public List<UserInfo> selectByInfos(UserInfo userInfo) {
        return userInfoMapper.select(userInfo);
    }

    @Override
    public List<UserInfo> findByAccount(String account) {
        return userInfoMapper.findByAccount(account);
    }

    @Override
    public List<UserInfoDto> findByDeptId(Integer deptId) {
        return userInfoMapper.findByDeptId(deptId);
    }

    @Override
    public void updateUserInfoAccountStatus(String accountStatus) {
        userInfoMapper.updateUserInfoAccountStatus(accountStatus);
    }

    @Override
    public void bindRole(UserInfoCreate create) {
        // 添加用户角色信息
        for (Integer roleId : create.getRoleIds()) {
            userRoleService.addUserRole(create.getUserId(), roleId);
        }
    }

    @Override
    public void bindWare(UserInfoCreate create, Integer createUserId) {
        // 添加用户仓库信息
        for (Integer wareId : create.getWareIds()) {
            wareUserService.addWareUser(create.getUserId(), wareId, createUserId);
        }

    }

    @Override
    public void bindOrganization(UserInfoCreate create) {
        // 添加用户货主信息
        for (Integer organizationId : create.getOrganizationIds()) {
            userOrganizationService.addUserOrganization(create.getUserId(), organizationId);
        }
    }

    @Override
    public void bindArea(UserInfoCreate create, Integer createUserId) {
        for (Integer areaId : create.getAreaIds()) {
            wareUserService.addAreaUser(create.getUserId(), areaId, createUserId);
        }
    }

    @Override
    public List<UserInfoDto> findList(UserInfoCriteria criteria) {
        return userInfoMapper.findList(criteria);
    }

    @Override
    public List<UserInfoDto> findAny(UserInfoCriteria criteria) {
        return userInfoMapper.findAny(criteria);
    }

    @Override
    public String paresUserExcel(String path) {
//        // 获取excel对象
//        Workbook workbook = ApExcelUtils.readExcel(path);
//        Sheet sheet = null;
//        Row row = null;
////        List<ItemInfo> itemList = new ArrayList<>();
//        if (workbook != null) {
//            // 获取第一个sheet工作表
//            sheet = workbook.getSheetAt(0);
//            // 获取最大行数(不包括空行)
//            int rownum = sheet.getPhysicalNumberOfRows();
//            // 获取最大列数
//            int colnum = sheet.getRow(1).getPhysicalNumberOfCells();
//            String cells = "";// 每格的值
//            for (int i = 1; i < rownum - 1; i++) {
//                row = sheet.getRow(i);
////                //物料对象
//                UserInfo item = new UserInfo();
//                // 遍历每行中的每列
//                for (int j = 0; j < colnum; j++) {
//                    Cell cell = row.getCell(j);
//                    if (cell == null || "".equals(cell)) {
//                        continue;
//                    }
//                    if (cell.toString().contains("-") && ApExcelUtils.checkDate(cell.toString())) {
//                        cells = ApExcelUtils.getCellValue(cell);
//                    } else {
//                        cell.setCellType(1);
//                        cells = (String) ApExcelUtils.getCellFormatValue(cell);
//                    }
//                    if (j == 0) {
//                        item.setAccount(cells);
//                    } else if (j == 1) {
//                        item.setPassword(cells);
//                    } else if (j == 2) {
//                        item.setUserName(cells);
//                    }  else if (j == 3) {
//                        if ("男".equals(cells)){
//                            item.setGender(1);
//                        }else {
//                            item.setGender(2);
//                        }
//                    }
//                   /* else if (j == 12) {
//                        item.setErpWareCode(cells);
//                    }*/
//
//                }
//                if(item.getAccount()!=null) {
//                    // itemList.add(item);
//                    save(item);
//                }
//            }
//            /*if (itemList != null && itemList.size() > 0) {
//                itemInfoMapper.insertAll(itemList);
//            }*/
//        }
        return "导入成功";
    }

}
